﻿namespace MF.HSD.CreateVoucherBP
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Text;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.GL.Voucher;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.PL;
    using UFSoft.UBF.Transactions;
    using UFSoft.UBF.Util.Context;
    using UFSoft.UBF.Util.DataAccess;

    /// <summary>
    /// CreateVoucher partial 
    /// </summary>	
    public partial class CreateVoucher
    {
        internal BaseStrategy Select()
        {
            return new CreateVoucherImpementStrategy();
        }
    }

    #region  implement strategy	
    /// <summary>
    /// Impement Implement
    /// 
    /// </summary>	
    internal partial class CreateVoucherImpementStrategy : BaseStrategy
    {
        public CreateVoucherImpementStrategy() { }

        public override object Do(object obj)
        {
            CreateVoucher bpObj = (CreateVoucher)obj;
            string result = "";

            using (UBFTransactionScope scope = new UBFTransactionScope(TransactionOption.RequiresNew))
            {
                //组织辅助段
                int orgSegment = 2;
                int maxValue = GetMaxNum();
                foreach (VoucherDTO srcDto in bpObj.VoucherDTO)
                {
                    try
                    {
                        //重写上下文
                        PlatformContext context = PlatformContext.Current;//取出当前上下文信息
                        string userCode = context.UserCode, entCode = context.EnterpriseID, cnCode = context.Default_Culture;
                        ContextDTO tdto = new ContextDTO();
                        tdto.UserCode = userCode;//用户编码
                        tdto.EntCode = entCode;//企业编码
                        tdto.CultureName = "zh-CN";//固定
                        tdto.OrgCode = srcDto.ToOrgCode;//组织编码
                        tdto.WriteToContext();
                        //账簿
                        UFIDA.U9.Base.SOB.SetofBooks book = UFIDA.U9.Base.SOB.SetofBooks.Finder.Find("SOBType = 0 and Org.ID='" + UFIDA.U9.Base.Context.LoginOrg.ID + "'", new OqlParam[] { });
                        if (book == null)
                        {
                            throw new Exception("匹配不到创建组织的主账簿数据！");
                        }
                        //源凭证
                        Voucher oldVoucher = Voucher.Finder.Find("VoucherDisplayCode='" + srcDto.VoucherNo + "' and Org.Code = '" + srcDto.OrgCode + "'");
                        //凭证头
                        List<UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportVoucherDTOData> vouchers = new List<UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportVoucherDTOData>();
                        //接口头信息
                        UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportVoucherDTOData dto = new UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportVoucherDTOData();
                        //凭证类型
                        UFIDA.U9.CBO.FI.VoucherCategory.VoucherCategory voucherCategory = UFIDA.U9.CBO.FI.VoucherCategory.VoucherCategory.Finder.Find("Code='04' and Org.Code= '"+ srcDto.ToOrgCode + "'"); 

                        dto.VoucherCategory = new CommonArchiveDataDTOData();
                        dto.VoucherCategory.ID = voucherCategory.ID;
                        //账簿
                        dto.SOB = new UFIDA.U9.CBO.Pub.Controller.CommonArchiveDataDTOData();
                        dto.SOB.Code = book.Code;
                        //私有段
                        dto.DescFlexField = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegmentsData();
                        dto.DescFlexField.PrivateDescSeg1 = "True";
                        dto.DescFlexField.PrivateDescSeg3 = srcDto.VoucherNo;

                        //接口行集合信息
                        dto.Entries = new List<UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportEntryDTOData>();
                        //凭证分录行号
                        int SerialNo = 10;
                        //制单日期
                        dto.CreateDate = DateTime.Today;
                        //现金流量项目
                        dto.CFVoucherItems = new List<UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportCFVoucherItemDTOData>();

                        //接口行信息
                        UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportEntryDTOData ldto = new UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportEntryDTOData();
                        //行号
                        ldto.SerialNo = SerialNo;
                        //摘要
                        ldto.Abstracts = "内部组织交易";
                        //科目
                        string accountCode = "8007";
                        for(int i = 1;i< maxValue; i++)
                        {
                            accountCode += "|0";
                        }
                        ldto.Account = new CommonArchiveDataDTOData();
                        ldto.Account.Code = accountCode;
                        //币种
                        ldto.Currency = new CommonArchiveDataDTOData();
                        ldto.Currency.Code = book.FunctionalCurrency.Code;
                        if(srcDto.TotalMoney> 0)
                        {
                            //贷方金额(本币)
                            ldto.AccountedCr = 0;
                            //借方金额(本币)
                            ldto.AccountedDr = srcDto.TotalMoney;
                            //贷方金额(原币)
                            ldto.EnteredCr = 0;
                            //借方金额(原币)
                            ldto.EnteredDr = srcDto.TotalMoney;
                        }
                        else
                        {
                            //贷方金额(本币)
                            ldto.AccountedCr = -srcDto.TotalMoney;
                            //借方金额(本币)
                            ldto.AccountedDr = 0;
                            //贷方金额(原币)
                            ldto.EnteredCr = -srcDto.TotalMoney;
                            //借方金额(原币)
                            ldto.EnteredDr = 0;
                        }
                        //汇率
                        // ldto.OCToFCExchangeRate = decimal.Parse(entry.ExchangeRate);
                        //行扩展字段
                        dto.Entries.Add(ldto);
                        SerialNo += 10;
                        //如果有报销明细，需要添加报销明细数据
                        if (srcDto.VoucherLineDTO != null && srcDto.VoucherLineDTO.Count > 0)
                        {
                            foreach (VoucherLineDTO line in srcDto.VoucherLineDTO)
                            {
                                ldto = new UFIDA.U9.ISV.GL.ISVGLImportSV.ISVImportEntryDTOData();
                                //行号
                                ldto.Description = new UFIDA.U9.Base.FlexField.DescFlexField.DescFlexSegmentsData();
                                ldto.Description.PrivateDescSeg1 = "True";
                                ldto.SerialNo = SerialNo;
                                //摘要
                                ldto.Abstracts = line.Account;//用于记录摘要
                                //科目
                                string AccountCode = line.AccountCode;
                                for (int i = 2; i <= maxValue; i++)
                                {
                                    if (i == orgSegment)
                                    {
                                        //需要判断该科目的组织段是否可用
                                        if(CheckAccountCode(line.AccountCode, srcDto.ToOrgCode))
                                            AccountCode += "|" + srcDto.ToOrgCode;
                                        else
                                            AccountCode += "|0";
                                    } 
                                    else if (i == int.Parse(line.SegmentNumber))
                                        AccountCode += "|" + line.SegmentValue;
                                    else
                                        AccountCode += "|0";
                                }
                                ldto.Account = new CommonArchiveDataDTOData();
                                ldto.Account.Code = AccountCode;
                                //币种
                                ldto.Currency = new CommonArchiveDataDTOData();
                                ldto.Currency.Code = book.FunctionalCurrency.Code;
                                //贷方金额(本币)
                                ldto.AccountedCr = line.MoneyCr;
                                //借方金额(本币)
                                ldto.AccountedDr = line.MoneyDr;
                                //贷方金额(原币)
                                ldto.EnteredCr = line.MoneyCr;
                                //借方金额(原币)
                                ldto.EnteredDr = line.MoneyDr;
                                dto.Entries.Add(ldto);
                                SerialNo += 10;
                            }
                        }
                        vouchers.Add(dto);
                        UFIDA.U9.ISV.GL.ISVGLImportSV.Proxy.ISVGLImportSVProxy proxy = new UFIDA.U9.ISV.GL.ISVGLImportSV.Proxy.ISVGLImportSVProxy();
                        proxy.ImportVoucherDTOs = vouchers;
                        proxy.TargetOrgCode = UFIDA.U9.Base.Context.LoginOrg.Code;
                        List<UFIDA.U9.ISV.GL.ISVGLImportSV.ISVReturnVoucherDTOData> isvrlist = proxy.Do(UFIDA.U9.Base.Context.LoginOrg.ID);
                        scope.Commit();
                        string DocNo = isvrlist[0].VoucherDisplayCode;
                        //将新凭证号更新到原凭证私有段
                        UpdateVoucherNo(oldVoucher, DocNo);
                    }
                    catch (Exception ex)
                    {
                        scope.Rollback();
                        throw new Exception(ex.Message);
                    }

                }
            }

            return result;
        }
        //获取最大辅助段数
        public int GetMaxNum()
        {
            int maxValue = 0;
            DataSet ds = new DataSet();
            string sql = @"select isnull(Max(e.Number),0) Number  from Base_KeyFlexFieldStru a
                inner join Base_KeyFlexFieldDef b on a.KeyFlexFieldDef = b.ID
                inner join Base_KeyFlexFieldStru_Trl c on a.ID = c.ID and c.SysMLFlag='zh-CN'
                inner join Base_KeyFlexSegment e on a.ID = e.KeyFlexFieldStru
                inner join Base_ValueSetDef vsd on vsd.ID = e.ValueSetDef
                inner join Base_ValueSetDef_Trl vsdt on vsdt.ID = e.ValueSetDef and vsdt.SysMLFlag='zh-CN'
                where dbo.F_GetEnumName('UFIDA.U9.Base.FlexField.KeyFlexField.KeyFlexNameEnum', b.KeyFlexName, 'zh-CN') = '科目' and c.Name = '会计科目'
				";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql.ToString(), null, out ds);
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                maxValue = int.Parse(ds.Tables[0].Rows[0]["Number"].ToString()) ;
            }
            return maxValue;
        }

        public void UpdateVoucherNo(Voucher voucher,string newVoucherNo)
        {
            string sql = "Update GL_Voucher set DescFlexField_PrivateDescSeg2 ='"+ newVoucherNo + "' where ID = '"+voucher.ID+"'";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql.ToString(), null);
        }
        //判断科目组织段是否可用
        public bool CheckAccountCode(string accountCode,string orgCode)
        {
            bool IsTrue = false;
            DataSet ds = new DataSet();
            string sql = @"select distinct nacc.Code,sob.Code,role.Segment2
	        from CBO_NaturalAccount nacc 
	        inner join CBO_NaturalAccountSet nas on nas.id = nacc.NaturalAccountSet
	        inner join CBO_NaturalAccountSOBProperty nasob on nacc.ID = nasob.NaturalAccount
	        inner join CBO_NaturalAccountSOBSegmentUseRole role on role.NaturalAccountSOBProperty = nasob.ID
	        inner join Base_SetofBooks sob on sob.ID=nasob.SOB
            inner join Base_Organization org on sob.Org = org.ID
	        where nas.Code='1' and nacc.Code='" + accountCode + @"' and org.Code='" + orgCode + "' ";
            DataAccessor.RunSQL(DataAccessor.GetConn(), sql.ToString(), null, out ds);
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["Segment2"].ToString() == "1")
                    IsTrue = true;
            }
            return IsTrue;
        }
    }

    #endregion


}